package com.example.sourcecodelearning.modules.designpattern.responsibilitychain;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

/**
 * @author yuzhenxin
 * @date 2023/8/1
 */
@Data
public class Request {

    private volatile Collection<Header> headers;

    private Object body;

    @Data
    @AllArgsConstructor
    public static class Header {
        private String key;
        private String value;
    }

    public boolean addHeader(String key, String value) {
        if (key == null) {
            return false;
        }
        if (headers == null) {
            synchronized (this) {
                if (headers == null) {
                    headers = new ArrayList<>();
                }
            }
        }
        Header header = new Header(key, value);
        return headers.add(header);
    }

    public String getHeader(String name) {
        if (CollectionUtils.isEmpty(headers)) {
            return null;
        }
        for (Header header : headers) {
            if (Objects.equals(header.getKey(), name)) {
                return header.getValue();
            }
        }
        return null;
    }

}
